<template>
  <div>
    <el-form :inline="true" label-position="left" label-width="84px">
      <el-form-item>
        <el-select filterable v-model="queryParams.tag" placeholder="请选择查询时间" clearable>
          <el-option label="领取时间" value="0"></el-option>
          <el-option label="使用时间" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-radio-group v-model="queryParams.timeTag" @change="handleRadioChange">
          <el-radio-button label="今天" />
          <el-radio-button label="7天" />
          <el-radio-button label="30天" />
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          @change="handleDateChange"
          v-model="queryParams.lifespanStartTime"
          type="datetime"
          placeholder="优惠券有效期开始时间"
          value-format="yyyy-MM-dd HH:mm:ss"
        />
      </el-form-item>
      <el-form-item>
        <el-date-picker
          @change="handleDateChange"
          v-model="queryParams.lifespanEndTime"
          type="datetime"
          placeholder="优惠券有效期结束时间"
          value-format="yyyy-MM-dd HH:mm:ss"
        />
      </el-form-item>
      <el-form-item>
        <el-select
          filterable
          clearable
          multiple
          v-model="queryParams.type"
          placeholder="请选择优惠券类型"
        >
          <el-option
            v-for="dict in dict?.type?.coupon_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          filterable
          v-model="queryParams.state"
          placeholder="请选择优惠券使用状态"
          clearable
        >
          <el-option label="未使用" value="0"></el-option>
          <el-option label="已使用" value="1"></el-option>
          <el-option label="已过期" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="queryParams.stadiumId"
          filterable
          remote
          reserve-keyword
          placeholder="请输入场馆名称"
          :remote-method="handleQueryStadium"
          clearable
        >
          <el-option
            v-for="item in stadiumOptions"
            :key="item.id"
            :label="item.stadiumName"
            :value="item.id"
          >
            <span style="float: left">{{ item.stadiumName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{
              item.stadiumName
            }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input v-model="queryParams.name" placeholder="请输入优惠券名称" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="queryParams.code" placeholder="请输入优惠券编码" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="queryParams.mobile" placeholder="请输入手机号" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
      </el-form-item>
      <el-button class="form_button excel_btn" @click="handleExport">导出</el-button>
    </el-form>
    <el-table :data="list">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column
        prop="code"
        label="优惠券编码"
        width="100"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="name"
        label="优惠券名称"
        width="120"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="优惠券类型" width="100" show-overflow-tooltip>
        <template #default="{ row }">
          <div v-for="item in dict?.type?.coupon_type" :key="item.value">
            <div v-if="item.value == String(row.discountType)">
              {{ item.label }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="使用条件" width="120" show-overflow-tooltip>
        <template #default="{ row }">
          <div v-if="row.type === 1 && row.discountType === 3 && row.useType === 2">
            订单满{{ row.useAmount }}元可用
          </div>
          <div v-else-if="row.type === 2 && row.discountType === 4 && row.cardType === 1">次卡</div>
          <div v-else-if="row.type === 2 && row.discountType === 4 && row.cardType === 2">周卡</div>
          <div v-else-if="row.type === 2 && row.discountType === 4 && row.cardType === 3">月卡</div>
          <div v-else>无门槛</div>
        </template>
      </el-table-column>
      <el-table-column
        prop="subCode"
        label="用户优惠券编号"
        width="150"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="nickName"
        label="用户名"
        width="110"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="mobile"
        label="手机号"
        width="110"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="使用状态" show-overflow-tooltip>
        <template #default="{ row }">
          <div v-if="row.state == '0'">未使用</div>
          <div v-else-if="row.state == '1'" style="color: rgba(42, 130, 228, 1)">已使用</div>
          <div v-else-if="row.state == '2'">已过期</div>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="使用时间" show-overflow-tooltip>
        <template #default="{ row }">
          <span class="color-0988FB">{{ row.updateTime }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="orderNo" label="关联订单" show-overflow-tooltip>
        <template #default="{ row }">
          <span class="color-0988FB">{{ row.orderNo }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="stadiumName" label="使用场馆" show-overflow-tooltip>
        <template #default="{ row }">
          <span class="color-0988FB">{{ row.stadiumName }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="领取时间" show-overflow-tooltip></el-table-column>
      <el-table-column label="有效期" width="150" show-overflow-tooltip>
        <template #default="{ row }">
          <div v-if="row.lifespanType === 1">领取当日{{ row.lifespanDay }}天有效</div>
          <div v-else-if="row.lifespanType === 2" class="leading-5">
            {{ row.lifespanStartTime }}
            <p class="text-center">至</p>
            {{ row.lifespanEndTime }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="80">
        <template #default="{ row }">
          <div class="table_btn">
            <el-button
              type="text"
              class="red_text"
              @click="handleDel(row)"
              v-hasPermi="['sys:coupons_count:btn_del']"
              >删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="queryParams.total > 0"
      :total="queryParams.total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useDict } from '@/utils/dict'
import { getStadiumInfo } from '@/api/stadium/stadium'
import { deleteCouponsUser, receiveHistoryPage } from '@/api/coupon/coupon'
import { ElMessageBox, ElMessage } from 'element-plus'

// 字典数据
const { dict } = useDict({
  dicts: ['coupon_type'],
})

// 定义响应式数据
const list = ref<any[]>([])
const stadiumOptions = ref<any[]>([])

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
  tag: null as string | null,
  timeTag: null as string | null,
  lifespanStartTime: null as string | null,
  lifespanEndTime: null as string | null,
  state: null as string | null,
  name: null as string | null,
  stadiumId: null as number | null,
  type: [] as string[],
  mobile: null as string | null,
  code: null as string | null,
})

// 初始化数据赋值
onMounted(() => {
  // 初始化数据赋值
  const currentDate = new Date() // 当前时间
  queryParams.lifespanStartTime = new Date(
    currentDate.toLocaleDateString() + ' ' + '00:00:00',
  ).toISOString()
  queryParams.lifespanEndTime = new Date(
    currentDate.toLocaleDateString() + ' ' + '23:59:59',
  ).toISOString()
  queryParams.tag = '0'
  queryParams.timeTag = '今天'
})

// 加载数据
const init = () => {
  getList()
}

// 监听单选框赋值开始时间结束时间
const handleRadioChange = (value: string) => {
  const currentDate = new Date() // 当前时间
  queryParams.lifespanEndTime = new Date(
    currentDate.toLocaleDateString() + ' ' + '23:59:59',
  ).toISOString()
  if (value == '今天') {
    queryParams.lifespanStartTime = new Date(
      currentDate.toLocaleDateString() + ' ' + '00:00:00',
    ).toISOString()
  } else if (value == '7天') {
    const sevenDaysAgo = new Date(currentDate.getTime() - 7 * 24 * 60 * 60 * 1000)
    queryParams.lifespanStartTime = new Date(
      sevenDaysAgo.toLocaleDateString() + ' ' + '00:00:00',
    ).toISOString()
  } else if (value == '30天') {
    const thirtyDaysAgo = new Date(currentDate.getTime() - 30 * 24 * 60 * 60 * 1000)
    queryParams.lifespanStartTime = new Date(
      thirtyDaysAgo.toLocaleDateString() + ' ' + '00:00:00',
    ).toISOString()
  }
}

// 监听开始时间结束时间 单选空不显示
const handleDateChange = (value: string) => {
  if (value != null) {
    queryParams.timeTag = null
  } else {
    queryParams.timeTag = null
  }
}

// 查询场馆
const handleQueryStadium = (query: string) => {
  if (query !== '') {
    getStadiumInfo({ stadiumName: query }).then((res: any) => {
      stadiumOptions.value = res.data
    })
  } else {
    stadiumOptions.value = []
  }
}

// 查询
const handleQuery = () => {
  queryParams.pageNum = 1
  console.log(queryParams)
  getList()
}

// 查询列表数据
const getList = () => {
  receiveHistoryPage(queryParams).then((res: any) => {
    queryParams.total = res.total
    list.value = res.rows
  })
}

// 删除
const handleDel = (val: any) => {
  ElMessageBox.confirm(`您确认删除这张优惠券吗？`)
    .then(() => {
      const ids = [val.id]
      deleteCouponsUser(ids).then((res: any) => {
        if (res.code == 200) {
          ElMessage.success(res.msg)
        } else {
          ElMessage.error(res.msg)
        }
        getList()
      })
    })
    .catch(() => {})
}

// 导出
const handleExport = () => {
  console.log(queryParams)
  // @ts-ignore
  download(
    'cj-stadium/sys/coupons/receiveHistoryExport',
    {
      params: queryParams,
    },
    `领取记录.xlsx`,
  )
}

// 暴露方法给父组件
defineExpose({
  init,
})
</script>

<style scoped lang="scss"></style>
